package org.rbreznak.tronco.client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import org.rbreznak.tronco.sql.SQLData;

public class Screen3 extends Screen{
	private static final long serialVersionUID = 1L;
	
	private JLabel directionsText = new JLabel();
	private JButton btnExit = new JButton(new ImageIcon("img/buttons/exit.png"));
	
	private String card="";
	private boolean reading=false;
	
	public Screen3() {
		setLayout(new BorderLayout());
		setBackground(new Color(0,0,0));
		
		FormatUI.formatLabel(directionsText);
		
		btnExit.setAlignmentX(Component.RIGHT_ALIGNMENT);
		
		FormatUI.formatImageButton(btnExit);
		
		add(btnExit, BorderLayout.SOUTH);
		add(directionsText, BorderLayout.NORTH);
		
		this.setVisible(true);
		
		
	}
	
	public void init() {
		directionsText.setText("Please Swipe Your ID Card Now");
		card="";
		reading=false;
	}
	
	public void keyPressed(KeyEvent e) {
	
		SQLData data;
		
		if(e.getKeyCode() > 30) {
			if(e.getKeyChar() == ';') {
				card = "";
				reading = true;
			} else if(e.getKeyChar() == '?') {
				reading = false;
			} else {
				if(reading && Character.isDigit(e.getKeyChar())) {
					card += e.getKeyChar();
				}
			}
		} else {
			reading = true;
		}
		
		if(!reading) {
			directionsText.setText(card);
			
			System.out.println(card);
			
			dbh.execute("SELECT * FROM users WHERE `userID` = '" + card + "' LIMIT 1;");
			
			data = dbh.getResults();
			if(data.getResults().size() > 0) {
				((Screen4) nodes.get(0)).setID(card);
				_fireScreenUpdate();
			} else {
				directionsText.setText("Invalid ID");
			}
		}
	}

	@Override
	public void decideNext() {
		if(nodes.size() > 0) {
			setNext(nodes.get(0));
		}
	}
	
	@Override
	public String toString() {
		return directionsText.getText();
	}

	@Override
	public void reset() {
		setNext(null);
	}
}
